package com.boco.pciv.controller.person;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ftp.Ftp;
import com.boco.pciv.controller.PcivController;
import com.boco.pciv.controller.company.CompanyController;
import com.boco.pciv.core.entity.*;
import com.boco.pciv.core.security.LoginUser;
import com.boco.pciv.core.util.UploadFileUtil;
import com.boco.pciv.service.company.ICompanyService;
import com.boco.pciv.service.person.IPersonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;

@RestController
@RequestMapping(value="/person/")
public class PersonControl extends PcivController {
    Logger logger = LoggerFactory.getLogger(PersonControl.class);

    @Resource
    private IPersonService iPersonService;
    /**
     * 民工查询
     */
    @GetMapping("/personCompanylist")
    public PageResultBase personCompanylist(LayUIPager pager, String bz_id) {
        SearchCriteria param = new SearchCriteria();
        param.setPager(pager);
        if (StrUtil.isNotBlank(bz_id)) {
            param.putCriteria("bz_id", bz_id);
        }
        LoginUser user = getCurUser();
        if(user.getUserType()!=0){
            param.putCriteria("licno", user.getDeptId());
        }

        //其他查询条件
        PageResultBase result = iPersonService.personCompanylist(param);
        return result;
    }

    @PostMapping("/fileUpload")
    public BizResponse fileUpload(MultipartFile file, String filePt) {
        LoginUser user=getCurUser();
        String filePath = "";
        try {
            String fileName = file.getOriginalFilename();
            if(fileName.contains("\\")){
                fileName=fileName.substring(fileName.lastIndexOf("\\") + 1);
            }
            logger.debug("get file:{}:{}", file.getOriginalFilename(), file.getName());
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
            String name = fileName.substring(0, fileName.lastIndexOf("."));
            String newFileName = String.format("%s-%s-%s.%s", name, user.getDeptId(),user.getUserId(), ext);
            String localFileName = UploadFileUtil.uploadFile(file, filePt, newFileName);
            logger.debug("save file:{}", localFileName);

//            Ftp ftp = new Ftp(ftpProperties.getIp(), ftpProperties.getPort(), ftpProperties.getUsername(), ftpProperties.getPassword(), Charset.forName("GBK"));
            String fileDir = UploadFileUtil.getBasePath();
            String pathName = fileDir + "/webapps/upload/" +filePt+"/"+ localFileName;
            //上传本地文件
            File upfile = FileUtil.file(pathName);
//            ftp.upload(ftpProperties.getPath(), localFileName, upfile);
//            ftp.close();
            return BizResponseUtil.single(localFileName);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR);
        }
    }

    @PostMapping("/download")
    public void fileDownload(String filePt,String fileName, HttpServletResponse response) {
        try {
//            Ftp ftp = new Ftp(ftpProperties.getIp(), ftpProperties.getPort(), ftpProperties.getUsername(), ftpProperties.getPassword(), Charset.forName("GBK"));
            String fileDir = UploadFileUtil.getBasePath();
//            String pathName = fileDir + "/download/"+filePt+"/" + fileName;
            String pathName = fileDir + "/webapps/upload/"+filePt+"/" + fileName;
            //下载本地文件
            File downFile = FileUtil.file(pathName);
//            ftp.download(ftpProperties.getPath(), fileName, downFile);
//            ftp.close();
            logger.debug("download file:{}", fileName);


            fileName = URLEncoder.encode(fileName,"UTF-8");
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名             
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                OutputStream os = response.getOutputStream();
                if(!downFile.exists()){
                    os.write("凭证文件已丢失".getBytes());
                }
                else {
                    fis = new FileInputStream(downFile);
                    bis = new BufferedInputStream(fis);
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
        }
    }

}
